package QRCG;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.servlet.annotation.WebServlet;

/**
 * Servlet implementation class LoginServe
 */
@WebServlet("/LoginServe")
public class LoginServe extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public static final String LOGIN_FAILED_MISMATCH = "Login Failed: Mismatch of nickname & password!";
	public static final String LOGIN_FAILED_FILLBLANKS = "Login Failed: Fill all the blanks!";


	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		HttpSession session = request.getSession(true);

		String nickname = request.getParameter("nickname");
		String password = request.getParameter("password");

		if (nickname != "" && password != "") {
			DatabaseManager dk = new DatabaseManager();

			try {
				dk.connect();
				// generating MD5 hash of the password
				String hashPassword = Util.getMD5Hash(password);
				if (dk.successfulLogin(nickname, hashPassword)) {
					session.setAttribute("nickname", nickname);
					session.setAttribute("password", hashPassword);
					
					String user_id = dk.getUserInformation(DatabaseManager.UserInformation.ID, nickname);
					System.out.println("Debug: USER ID "+user_id);
					session.setAttribute("user_id", user_id);
					

					// getting email of the user and creating cookies
					String email = dk.getUserInformation(DatabaseManager.UserInformation.EMAIL, nickname);
					if (email == null) {
						email = "";
					}
					CookieManager.addSessionCookies(response, nickname, hashPassword, email);
					
					String keyword = (String) session.getAttribute("keyword");
					String gameId = (String) session.getAttribute("game_id");
					if(Util.hasTextContent(keyword)) {
						response.sendRedirect("PlayGame.jsp?game_id=" + gameId + "&keyword=" + keyword);
					} else {
						response.sendRedirect("UserMainPage.jsp");
					}
				}

				else {
					session.setAttribute("error_msg", LOGIN_FAILED_MISMATCH);
					response.sendRedirect("index.jsp");
				}

			} catch (Exception e) {
				e.printStackTrace();
				System.err.println("An error occured while connecting to the database");
			} finally{
				dk.close();
			}

		} else {
			session.setAttribute("error_msg", LOGIN_FAILED_FILLBLANKS);
			response.sendRedirect("index.jsp");

		}

	}

}
